package org.example.edusmart.config.security;


import org.example.edusmart.pojo.LoginUserPojo;
import org.example.edusmart.pojo.UserPojo;
import org.example.edusmart.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


@Service
public class LoadUserByUsername implements UserDetailsService {

    @Autowired
    private UserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户信息
        UserPojo queryUser = userService.checkUserByUsername(username);
        //判断用户是否存在
        if (Objects.isNull(queryUser)) {
            throw new RuntimeException("用户名不存在,请确定是否注册过账号");
        }
        //TODO 查询对应的权限信息
        List<String> permissions = userService.checkPermission(queryUser.getUserId());
        //把数据封装为UserDetails对象
        return new LoginUserPojo(queryUser, permissions);
    }
}
